#=====================================================================
# 2020/07/27
# Geothermal prediction dataviz
# Fumiya Uchikoshi, uchikoshi@princeton.edu
#=====================================================================
rm(list=ls())
######################################################################
# Loading packages
######################################################################
library(tidyverse) 
library(memisc)
library(dplyr)
library(tidyr) 
library(xtable)
library(ggplot2)
library(ggthemes)
library(lattice)

######################################################################
# Previous expl
######################################################################

df <- read_dta("../Data/imp.dta") %>% 
  dplyr::select(year:fourdiv4)

var <- c("unemployment","farming", "income", "married_male", "under15",
"construction", "ldpvote", "turnout", "totcwins", "onsenchi_std", "logpop",
"health", "crime", "homerate")

dfx <- df %>% dplyr::select(var,mi=`_mi_m`) %>% 
  mutate(imp = ifelse(mi>0,"Imputed","Observed"),
    mi = factor(mi),
    onsenchi_std = 1000* onsenchi_std) %>% 
  pivot_longer(
    cols = var,
    names_to = c("var"),
    values_to = c("value")) %>% 
  mutate(var = case_when(
    var == "unemployment" ~ "Unemployment rate",
    var == "farming" ~ "% farming",
    var == "income" ~ "Real income PC",
    var == "married_male" ~ "% married male",
    var == "under15" ~ "% under age 15",
    var == "construction" ~ "% construction",
    var == "ldpvote" ~ "LDP % vote",
    var == "turnout" ~ "Voter turnout",
    var == "totcwins" ~ "# LDP candidate wins",
    var == "onsenchi_std" ~ "# onsen ryokan std.",
    var == "homerate" ~ "Home ownership rate",
    var == "crime" ~ "Crime rate",
    var == "health" ~ "Muni. debt dependence ",
    var == "logpop" ~ "Logged pop. density"
  ))

ggplot(dfx,aes(value, color = imp, group = mi)) +
  geom_density() + facet_wrap(~var,scales = "free")+
  theme_few()+theme(legend.title=element_blank(),legend.position="bottom")+
  xlab("")+ylab("Density")

ggsave(height=6,width=9,dpi=200, filename="../Results/A3[MI_kernel].pdf",  family = "Helvetica")
